from contract import *
import json

# --- 工具方法
bootstrap()
# 数据采集
collected = {
    '_env': 'prod',
}


def collect(name, data):
    collected[name] = {
        'data': data,
    }


def get_stats_block_range():
    current = get_current_block_height()
    return range(current - 10, current)

# 节点信息校验


def validate_node(node):
    assert 'id' in node
    assert 'host' in node or 'ip' in node
    assert 'p2p_port' in node

# --- 测试流程

# --- 1. 系统状态


# 获取参与组网的全部节点信息
nodes = get_network_nodes()
assert type(nodes) is list
for node in nodes:
    validate_node(node)
collect('get_network_nodes', nodes)

# --- 2. 账本统计

# 当前区块高度
current_block_height = get_current_block_height()
assert type(current_block_height) is int
collect('get_current_block_height', current_block_height)

# 根据区块高度获取区块信息
block = get_block(height=current_block_height)
assert type(block) is dict
assert 'height' in block
assert 'hash' in block
assert 'timestamp' in block
assert 'full_json' in block
assert 'tx_count' in block
collect('get_block', block)

# 获取创世区块信息
genesis_block = get_block(height=0)
collect('genesis_block', genesis_block)

# 根据区块高度获取交易列表
tx_list = get_tx_by_block(height=current_block_height)
assert type(tx_list) is list
assert len(tx_list) > 0
for tx in tx_list:
    assert 'txid' in tx
collect('get_tx_by_block', tx_list)

# 根据交易ID获取交易列表
tx1 = get_tx_by_id(tx_list[0]['txid'])
assert type(tx1) is dict
assert 'txid' in tx1
assert 'timestamp' in tx1
assert 'full_json' in tx1
collect('get_tx_by_id', tx1)

stats = {
    'tx_count_max': 0,
    'tx_count_min': 0,
    'tx_count_avg': 0,
    'tx_total': 0,
    'block_count': 0,
}
for height in get_stats_block_range():
    block = get_block(height)
    tx_count = int(block['tx_count'], 0)
    stats['tx_count_max'] = max(stats['tx_count_max'], tx_count)
    stats['tx_count_min'] = min(stats['tx_count_min'], tx_count)
    stats['block_count'] += 1
    stats['tx_total'] += tx_count
collect('stats', stats)

with open('collected-prod.json', 'w') as f:
    json.dump(collected, f, indent=2)
